﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Scheduler;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Shell;

namespace PhoneApp1
{
    public partial class MainPage : PhoneApplicationPage
    {
        IEnumerable<ScheduledNotification> notifications;

        private IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;

 

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            System.Windows.Threading.DispatcherTimer dt = new System.Windows.Threading.DispatcherTimer();
            dt.Interval = new TimeSpan(0, 0, 0, 0, 200); // 200 Milliseconds
            dt.Tick += new EventHandler(dt_Tick);
            dt.Start();

            updateLiveTile();

        }
        /**
        * Set up the Live Tile here.
        * If an alarm is set it will display "Alarm set" as the secondary tile
        * Otherwise it will display "No alarm set".
        * */
        public void updateLiveTile()
        {
            // Application Tile is always the first Tile, even if it is not pinned to Start.
            ShellTile TileToFind = ShellTile.ActiveTiles.First();

            // Make sure the application is found otherwise there is no need to continue.
            if (TileToFind != null)
            {

                String backTileText;
                if (isAnyAlarmSet() == true)
                {
                    backTileText = "Alarm Set";
                }
                else
                {
                    backTileText = "No Alarm Set";
                }

                // Set the properties to update for the Application Tile.
                // Empty strings for the text values and URIs will result in the property being cleared.
                StandardTileData NewTileData = new StandardTileData
                {
                    //    Title = "dddd",   // This will not display since the default color is white
                    //     BackgroundColor = "",
                    BackgroundImage = new Uri("Images/tile/TileFront.jpg", UriKind.Relative),
                    BackTitle = backTileText,
                    BackBackgroundImage = new Uri("Images/tile/TileBack.jpg", UriKind.Relative)
                    // BackContent = textBoxBackContent.Text
                };

                // Update the Application Tile
                TileToFind.Update(NewTileData);
            }
        }

        // Credits to Jace Rhea at StackOverflow
        // http://stackoverflow.com/questions/3265715/is-there-a-timer-control-for-windows-phone-7
        //  This method is called every 200 ms and watches out for any
        // interactions with the alarm. If an alarm does go off it will 
        // point the user to the math puzzle page
        void dt_Tick(object sender, EventArgs e)
        {
            // Credits to
            // for explaining how to detect an alarm as MS clearly lack this
            // functionality in their alarm class
            // http://vigneshradhakrishnan.blogspot.co.uk/2012/02/detect-alarm-entrywp7.html
            try
            {
                // Get the reference for any alarms that may be active
                ScheduledAction a1 = ScheduledActionService.Find("student_alarm_clock_1");

                if (a1 != null)
                {
                    // Is this alarm active? wohooo then we need to go to the relevant puzzle page
                    if ((a1.IsEnabled == true) && (a1.IsScheduled == false))
                    {

                        // Ok check if there is a puzzle type stored. Technically
                        // this scenario should NEVER happen but error checking does no harm.
                        if (!appSettings.Contains("puzzle_type"))
                        {
                            MessageBox.Show("No puzzle type found.");
                            return;
                        }
                        if (appSettings["puzzle_type"].Equals("math")) 
                        {
                            // Navigate to the math puzzle page accordingly
                            NavigationService.Navigate(new Uri("/MathPuzzle.xaml", UriKind.RelativeOrAbsolute));
                        }
                        else if (appSettings["puzzle_type"].Equals("sequence")) 
                        {
                            // Navigate to the sequence puzzle
                            NavigationService.Navigate(new Uri("/SequencePuzzle.xaml", UriKind.RelativeOrAbsolute));
                        }
                        else
                        {
                            Console.WriteLine("Unknown alarm puzzle solve type.");
                            MessageBox.Show("Unknown alarm puzzle solve");
                        }
                    }
                }
            }
            catch
            {

            }
        }
        public void ResetItemsList()
        {
            // Use GetActions to retrieve all of the scheduled actions
            // stored for this application. The type <Reminder> is specified
            // to retrieve only Reminder objects.
            notifications = ScheduledActionService.GetActions<ScheduledNotification>();

            // If there are 1 or more reminders, hide the "no reminders"
            // TextBlock. IF there are zero reminders, show the TextBlock.
            //if (reminders.Count<Reminder>() > 0)
            if (notifications.Count<ScheduledNotification>() > 0)
            {
                EmptyTextBlock.Visibility = Visibility.Collapsed;
            }
            else
            {
                EmptyTextBlock.Visibility = Visibility.Visible;
            }

            // Update the ReminderListBox with the list of reminders.
            // A full MVVM implementation can automate this step.
            NotificationListBox.ItemsSource = notifications;

            updateLiveTile();
        }


        /**
         * Return a boolean: 1 if an alarm is set otherwise 0
         * */
        private Boolean isAnyAlarmSet()
        {
            // Get the reference for any alarms that may be active
            ScheduledAction a1 = ScheduledActionService.Find("student_alarm_clock_1");

            if (a1 != null)
            {
                return true;
            } else {

                return false;
            }
        }


        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            //Reset the ReminderListBox items when the page is navigated to.
            ResetItemsList();
        }

        private void deleteButton_Click(object sender, RoutedEventArgs e)
        {
            // The scheduled action name is stored in the Tag property
            // of the delete button for each reminder.
            string name = (string)((Button)sender).Tag;

            // Call Remove to unregister the scheduled action with the service.
            ScheduledActionService.Remove(name);

            // Reset the ReminderListBox items
            ResetItemsList();
        }

        /**
         * This method is called when the AddAlarm button is tapped
         * */
        private void ApplicationBarAddButton_Click(object sender, EventArgs e)
        {
            // Navigate to the AddReminder page when the add button is clicked.
            NavigationService.Navigate(new Uri("/AddAlarm.xaml", UriKind.RelativeOrAbsolute));
        }

        /**
         * Called when the About button is pressed
         */
        private void ApplicationBarAboutButton_Click(object sender, EventArgs e)
        {
            // Navigate to the AddReminder page when the add button is clicked.
            NavigationService.Navigate(new Uri("/AboutPage.xaml", UriKind.RelativeOrAbsolute));
        } 
    }
}